<template>
  <div>
    <el-tree
      ref="tree"
      default-expand-all
      node-key="id"
      show-checkbox
      check-strictly
      :data="list"
      :props="{label:'name',children:'children'}"
    />
    <el-row type="flex" justify="end" height="60">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button type="info" @click="$emit('close')">取消</el-button>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { transDataToTreeData } from '@/utils/index'
import { getRoleDetail, assignPerm } from '@/api/settings'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 实现给员工添加角色
    async hSubmit() {
      try {
        const permIds = this.$refs.tree.getCheckedKeys()
        const res = await assignPerm({ id: this.roleId, permIds: permIds })
        if (res.code !== 10000) this.$message.error(res.message) // 添加失败提示
        // 添加成功提示
        this.$message.success(res.message)
        // 关闭弹层
        this.$emit('close')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('获取权限列表', res)
        if (res.code === 10000) {
          // transDataToTreeData // 将平铺的数据转换为树形的数据
          this.list = transDataToTreeData(res.data)
          const info = await getRoleDetail(this.roleId)
          console.log('info', info)
          // info.data.permIds ===> ['604f7e17f900be1850edb154']
          this.$refs.tree.setCheckedKeys(info.data.permIds)
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style>

</style>
